#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<time.h>
#include<math.h>

#define width 600
#define height 600
#define Amount 1000
#define MinRadius 5
#define MaxRadius 50
#define PauseTime 50

void DrawCircle1(int x,int y,int r);
void DrawCircle2(int x,int y,int r);
int main()
{
	initgraph(width,height);
	setbkcolor(RGB(255,255,255));
	cleardevice();//以背景颜色清空背景
	srand(time(0));//随机种子函数

	int x,y,r;//横、纵坐标；半径

	//存储横、纵坐标和半径的数组
	int xArray[Amount];
	int yArray[Amount];
	int rArray[Amount];

	int count=0;//记录已生成圆的数量
	
	int DrawCircle=1;
	
	while(count<=Amount)
	{
		int exit=0;
		//随机生成坐标和半径
		x=rand()%width;
		y=rand()%height;
		r=MinRadius+rand() % (MaxRadius-MinRadius);

		//小球数量大于等于1时
		if(count>=1)
		{
			int i=0;
			//遍历检测是否与前面的圆有重合部分
			while(i<count)
			{
				if(kbhit())//当按键时
				{
					char input=_getch();
					if(input==' ')
					{
						count=0;//清空已生成圆
						cleardevice();//清屏
						//DrawCircle是1就++变成2；DrawCircle是2就--变成1
						if(DrawCircle==1)
						{
							DrawCircle++;
						}else
						{
							DrawCircle--;
						}
					}
				}

				int D1,D2;
				D1=(r+rArray[i])*(r+rArray[i]);//半径和的平方
				D2=(x-xArray[i])*(x-xArray[i])+(y-yArray[i])*(y-yArray[i]);//圆心距的平方
				//如果D1>D2，exit=1表示已经重合，并结束遍历
				if(D1>=D2)
				{
					exit=1;
					break;
				}
				//如果D1<=D2，i+=1并继续循环;
				i++;
			}
		}
		//如果exit==1，则重新开始循环
		if(exit==1)
		{
			continue;
		}

		//记录随机圆的坐标和半径
		xArray[count]=x;
		yArray[count]=y;
		rArray[count]=r;

		//随机颜色
		setfillcolor(RGB(rand()%255,rand()%255,rand()%255));
		//绘制圆
		if(DrawCircle==1)
		{
			DrawCircle1(x,y,r);
		}else
		{
			DrawCircle2(x,y,r);
		}
		count++;
		//时间间隔
		Sleep(PauseTime);
	}
	_getch();
	return 0;
}
void DrawCircle1(int x,int y,int r)
{
	while(r>0)
	{
		float h =rand()%360;
		COLORREF color=HSVtoRGB(h,0.6,0.8);
		setlinecolor(RGB(255,255,255));
		setfillcolor(RGB(rand()%255,rand()%255,rand()%255));
		fillcircle(x,y,r);
		r-=5;
	}
}
void DrawCircle2(int x,int y,int r)
{
	setfillcolor(RGB(rand()%255,rand()%255,rand()%255));
	fillcircle(x,y,r);
}